<template>
  <div class="tools-wrap">
    <div class="tools-item-wrap">
      <div
        class="tools-item"
        v-for="item in options"
        :key="item.name"
        @click="changeDrawMode(item.geometry)"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>

<script>
// import ...
var activeShapePoints = [];
var floatingPoint = null;
import * as Cesium from "cesium/Cesium";
export default {
  name: "maptools",
  components: {},
  data() {
    return {
      activeShape: null,
      viewer: null,
      options: [
        {
          title: "点",
          name: "点",
          geometry: "point",
          imgSrc: "",
        },
        {
          title: "线",
          name: "线",
          geometry: "line",
          imgSrc: "",
        },
        {
          title: "面",
          name: "面",
          geometry: "polygon",
          imgSrc: "",
        },
        {
          title: "圆",
          name: "圆",
          geometry: "circle",
          imgSrc: "",
        },
        {
          title: "矩形",
          name: "矩",
          geometry: "rectangle",
          imgSrc: "",
        },
        {
          title: "圆锥",
          name: "锥",
          geometry: "cone",
          imgSrc: "",
        },
        {
          title: "轨道",
          name: "轨",
          geometry: "orbit",
          imgSrc: "",
        },
        {
          title: "",
          name: "",
          imgSrc: "",
        },
        {
          title: "退出",
          name: "退",
          imgSrc: "",
        },
        {
          title: "编辑",
          name: "编",
          imgSrc: "",
        },
      ],
      drawingMode: "",
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.$nextTick(() => {
      this.viewer = window.$_baseMap3D;
      this.initEventHandler();
    });
  },
  methods: {
    changeDrawMode(geometry) {
      this.drawingMode = geometry;
    },
    initEventHandler() {
      var handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas);
      //双击鼠标左键清除默认事件
      this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      //初始化为线
      this.drawingMode = "line";

      //鼠标左键
      handler.setInputAction((event) => {
        // We use `viewer.scene.pickPosition` here instead of `viewer.camera.pickEllipsoid` so that
        // we get the correct point when mousing over terrain.
        var earthPosition = this.viewer.scene.pickPosition(event.position);
        // `earthPosition` will be undefined if our mouse is not over the globe.
        if (Cesium.defined(earthPosition)) {
          if (activeShapePoints.length === 0) {
            floatingPoint = this.createPoint(earthPosition);
            activeShapePoints.push(earthPosition);
            var dynamicPositions = new Cesium.CallbackProperty(() => {
              if (this.drawingMode === "polygon") {
                return new Cesium.PolygonHierarchy(activeShapePoints);
              }
              return activeShapePoints;
            }, false);
            this.activeShape = this.drawShape(dynamicPositions); //绘制动态图
          }
          activeShapePoints.push(earthPosition);
          this.createPoint(earthPosition);
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //鼠标移动
      handler.setInputAction((event) => {
        if (Cesium.defined(floatingPoint)) {
          var newPosition = this.viewer.scene.pickPosition(event.endPosition);
          if (Cesium.defined(newPosition)) {
            floatingPoint.position.setValue(newPosition);
            activeShapePoints.pop();
            activeShapePoints.push(newPosition);
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      handler.setInputAction((event) => {
        this.terminateShape();
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },

    //绘制点
    createPoint(worldPosition) {
      var point = this.viewer.entities.add({
        position: worldPosition,
        point: {
          color: Cesium.Color.WHITE,
          pixelSize: 5,
          outlineWidth: 3,
          outlineColor: Cesium.Color.RED,
          // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
      });
      return point;
    },

    //绘制图形
    drawShape(positionData) {
      var shape;
      if (this.drawingMode === "line") {
        shape = this.viewer.entities.add({
          polyline: {
            positions: positionData,
            clampToGround: true,
            width: 3,
          },
        });
      } else if (this.drawingMode === "polygon") {
        shape = this.viewer.entities.add({
          polygon: {
            hierarchy: positionData,
            material: new Cesium.ColorMaterialProperty(
              Cesium.Color.WHITE.withAlpha(0.7)
            ),
          },
        });
      } else if (this.drawingMode === "circle") {
        //当positionData为数组时绘制最终图，如果为function则绘制动态图
        var value =
          typeof positionData.getValue === "function"
            ? positionData.getValue(0)
            : positionData;
        //var start = activeShapePoints[0];
        //var end = activeShapePoints[activeShapePoints.length - 1];
        //var r = Math.sqrt(Math.pow(start.x - end.x, 2) + Math.pow(start.y - end.y, 2));
        //r = r ? r : r + 1;
        shape = this.viewer.entities.add({
          position: activeShapePoints[0],
          name: "Blue translucent, rotated, and extruded ellipse with outline",
          type: "Selection tool",
          ellipse: {
            semiMinorAxis: new Cesium.CallbackProperty(function () {
              //半径 两点间距离
              var r = Math.sqrt(
                Math.pow(value[0].x - value[value.length - 1].x, 2) +
                  Math.pow(value[0].y - value[value.length - 1].y, 2)
              );
              return r ? r : r + 1;
            }, false),
            semiMajorAxis: new Cesium.CallbackProperty(() => {
              var r = Math.sqrt(
                Math.pow(value[0].x - value[value.length - 1].x, 2) +
                  Math.pow(value[0].y - value[value.length - 1].y, 2)
              );
              return r ? r : r + 1;
            }, false),
            material: Cesium.Color.BLUE.withAlpha(0.5),
            outline: true,
          },
        });
      } else if (this.drawingMode === "rectangle") {
        //当positionData为数组时绘制最终图，如果为function则绘制动态图
        var arr =
          typeof positionData.getValue === "function"
            ? positionData.getValue(0)
            : positionData;
        shape = this.viewer.entities.add({
          name: "Blue translucent, rotated, and extruded ellipse with outline",
          rectangle: {
            coordinates: new Cesium.CallbackProperty(() => {
              var obj = Cesium.Rectangle.fromCartesianArray(arr);
              //if(obj.west==obj.east){ obj.east+=0.000001};
              //if(obj.south==obj.north){obj.north+=0.000001};
              return obj;
            }, false),
            material: Cesium.Color.RED.withAlpha(0.5),
          },
        });
      }
      return shape;
    },

    // Redraw the shape so it's not dynamic and remove the dynamic shape.
    terminateShape() {
      activeShapePoints.pop(); //去除最后一个动态点
      if (activeShapePoints.length) {
        this.drawShape(activeShapePoints); //绘制最终图
      }
      this.viewer.entities.remove(floatingPoint); //去除动态点图形（当前鼠标点）
      this.viewer.entities.remove(this.activeShape); //去除动态图形
      floatingPoint = undefined;
      this.activeShape = undefined;
      activeShapePoints = [];
    },
  },
  created() {},
  beforeDestroy() {},
};
</script>
<style lang="scss" scoped>
// @import url(); 引入公共css类
.tools-wrap {
  position: absolute;
  right: 40px;
  top: 40px;
  z-index: 99;
  .tools-item-wrap {
    background-color: rgba(55, 55, 55, 0.7);
    display: flex;
    border-radius: 10px;
    padding: 0px 10px;
    .tools-item {
      color: #fff;
      font-size: 14px;
      padding: 5px;
      &:hover {
        background-color: rgba(240, 240, 240, 0.7);
      }
    }
  }
}
</style>
